package com.woniu.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.common.CommonResult;
import com.woniu.dto.MenusDTO;
import com.woniu.exception.MenuServiceException;
import com.woniu.pojo.Admin;
import com.woniu.pojo.Menus;
import com.woniu.service.MenusService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/menus")
@Api(tags ="菜单管理")
public class MenusController {

    @Autowired
    private MenusService menusService;

    /**
     * 加载左侧导航菜单数据
     * @return
     */
    @RequestMapping("/getMenus")
    @ResponseBody
    @ApiOperation(value = "加载主页菜单数据")
    public List<MenusDTO> getMenus(){
        //根据当前登录用户的角色来获取该用户能够访问哪些资源
        Admin admin = (Admin) SecurityUtils.getSubject().getPrincipal();
        List<MenusDTO> list = menusService.findMenusByRoles(admin.getRoleId());
        return list;
    }

    /**
     * 加载树形菜单的数据
     * @return json格式的字符
     */
    @RequestMapping("/loadTree")
    @ResponseBody
    @ApiOperation(value = "加载树形菜单的数据")
    public String loadTree(){
        List<Menus> menus = menusService.findAll();
        ObjectMapper mapper = new ObjectMapper();
        try {
            String jsonStr = mapper.writeValueAsString(menus);
            return jsonStr;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 根据角色id加载默认选中的菜单数据
     * @param id
     * @return
     */
    @RequestMapping("/loadCheckTree/{roleId}")
    @ResponseBody
    @ApiOperation(value = "根据角色id查询菜单数据")
    @ApiImplicitParam(name = "id",value = "角色ID值",dataType = "Integer")
    public String loadCheckTree(@PathVariable("roleId")Integer id){
        List<Menus> list = menusService.findCheckMenusByRoleId(id);
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(list);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 查询菜单列表的数据
     * @return
     */
    @GetMapping("/loadMenus")
    @ResponseBody
    @RequiresPermissions("sys:menu:list")
    @ApiOperation(value = "查询菜单列表的数据")
    public Map loadMenus(){
        List<Menus> menus = menusService.findAll();
        Map result = new HashMap();
        result.put("code","0");
        result.put("msg","success");
        result.put("data",menus);
        return result;
    }

    /**
     * 导航到添加菜单的页面
     * @param model
     * @param parentId
     * @return
     */
    @RequestMapping("/addMenu/{parentId}")
    @ApiOperation(value = "导航到添加菜单的页面")
    public String addMenu(Model model,@PathVariable("parentId") Long parentId){
        model.addAttribute("parentId",parentId);//添加菜单节点的父Id
        return "/sys/addMenu";
    }

    /**
     * 添加菜单
     * @param menus
     * @return
     */
    @PostMapping("/saveMenu")
    @ResponseBody
    @RequiresPermissions("sys:menu:save")
    @ApiOperation(value = "添加菜单")
    @ApiImplicitParam(name = "menus",value = "添加菜单信息")
    public CommonResult saveMenu(Menus menus){
        //验证同级目录下的菜单节点名称不能重复
        if(menusService.checkMenuName(menus)){
            return CommonResult.failed("同级目录下节点的名称不能重复");
        }
        try {
            menusService.saveMenus(menus);
            return CommonResult.success("添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("添加失败");
        }
    }

    /**
     * 删除菜单
     * @param mid
     * @return
     */
    @DeleteMapping("/del/{id}")
    @ResponseBody
    @RequiresPermissions("sys:menu:delete")
    @ApiOperation(value = "删除菜单")
    @ApiImplicitParam(name = "id",value = "菜单列表id",dataType = "Integer")
    public CommonResult del(@PathVariable("id") Integer mid){
        try {
            menusService.delMenus(mid);
            return CommonResult.success("删除成功");
        } catch (MenuServiceException e) {
            e.printStackTrace();
            return CommonResult.failed(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("删除失败");
        }
    }

    /**
     * 导航到菜单编辑页面
     * @param model
     * @param menuId
     * @return
     */
    @RequestMapping("/editMenu/{menuId}")
    @ApiOperation(value = "导航到编辑菜单页面")
    public String updateMenu(Model model,@PathVariable("menuId") Integer menuId){
        //查询该menuId下的数据
        Menus menus=menusService.findByMenuId(menuId);
        model.addAttribute("menus",menus);//查询到的menu表数据存入model
        return "sys/editMenu";
    }

    /**
     * 菜单编辑
     * @return
     */
    @PutMapping("/editMenu")
    @ResponseBody
    @RequiresPermissions("sys:menu:update")
    @ApiOperation(value = "菜单编辑")
    @ApiImplicitParam(name = "menus",value = "修改菜单信息")
    public CommonResult updateMenus(Menus menus){
        try {
            menusService.updateMenus(menus);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("更新失败");
        }
        return CommonResult.success("更新成功");

    }

    /**
     * 更新sorting排序
     * @param menuId
     * @param sorting
     * @return
     */
    @PutMapping("/updateMenusSorting")
    @ResponseBody
    @ApiOperation(value = "菜单排序")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "menuId",value = "菜单ID",dataType = "Integer"),
            @ApiImplicitParam(name = "sorting",value = "排序数值")
    })
    public CommonResult updateMenusSorting(Integer menuId, String sorting){
        try {
            Integer.parseInt(sorting);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return CommonResult.failed("请输入数字");
        }
        try {
            menusService.updateMenusSorting(menuId,Integer.parseInt(sorting));
            return CommonResult.success("更新成功");
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return CommonResult.failed("更新失败");
        }

    }
}
